package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Autowired
    private ISeckillVoucherService seckillVoucherService;

    @Autowired
    private RedisIdWorker redisIdWorker;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    //事务代理对象
    private IVoucherOrderService proxy;

    //异步处理线程池
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();
    //基于JVM创建的消息阻塞队列
    private BlockingQueue<VoucherOrder> orderTasks =new ArrayBlockingQueue<>(1024 * 1024);

    private String queueName = "stream.orders";

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("sekillLock.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

//    @Override
//    public Result seckillVoucher(Long voucherId) {
//        //1.根据优惠券Id获取优惠券信息
//        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
//
//        //2.判断优惠券是否在期限内
//        LocalDateTime beginTime = voucher.getBeginTime();
//        LocalDateTime endTime = voucher.getEndTime();
//        if (beginTime.isAfter(LocalDateTime.now())){
//            return Result.fail("优惠券还未开始抢购!");
//        }
//        if (endTime.isBefore(LocalDateTime.now())){
//            return Result.fail("优惠券抢购已结束!");
//        }
//
//        //3.判断优惠券数量是否充足
//        Integer stock = voucher.getStock();
//        if (stock < 1 ){
//            return Result.fail("优惠券数量不足！");
//        }
//
//        Long userId = UserHolder.getUser().getId();
//        //获取锁工具类
////        SimpleRedisLock simpleRedisLock = new SimpleRedisLock("order:"+userId,stringRedisTemplate);
//        RLock lock = redissonClient.getLock("lock:order:" + userId);
//        //获取锁
//        boolean isLock = lock.tryLock();
//        if (!isLock){
//            //获取锁失败，这里是抢单业务，直接响应失败即可，无需重试
//            return Result.fail("不允许重复抢单！");
//        }
//
//        try {
//            //获取代理对象，通过代理对象来调用方法 防止事务失效
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.createVoucherOrder(voucherId);
//        } finally {
//            lock.unlock();
//        }
//
//    }

    //在类初始化之后执行，启动获取消息的线程。
    @PostConstruct
    public void init(){
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    private class VoucherOrderHandler implements Runnable {
        @Override
        public void run() {
            while (true){
                try {
                    log.info("===========开始运行消息队列监听线程===========");
                    // 1.获取stream消息队列中的订单信息 xreadgroup group g1 c1 count 1 block 2000 streams stream.orders >
                    List<MapRecord<String, Object, Object>> mapRecordList = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create("stream.orders", ReadOffset.lastConsumed())
                    );
                    //2.若消息队列为空，则继续下一次循环
                    if (mapRecordList == null || mapRecordList.isEmpty()){
                        continue;
                    }
                    //3.转换订单信息
                    MapRecord<String, Object, Object> record = mapRecordList.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);

                    // 4.创建订单
                    handleVoucherOrder(voucherOrder);

                    //5.确认消息
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());
                    log.info("===========成功消费并确认消息===========");
                } catch (Exception e) {
                    log.error("处理订单异常", e);
                    handlePendingList();
                }
            }
        }
    }

    private void handlePendingList() {
        while (true){
            try {
                // 1.获取pend-list中的订单信息 xreadgroup group g1 c1 count 1 streams stream.orders 0
                List<MapRecord<String, Object, Object>> mapRecordList = stringRedisTemplate.opsForStream().read(
                        Consumer.from("g1", "c1"),
                        StreamReadOptions.empty().count(1),
                        StreamOffset.create("stream.orders", ReadOffset.from("0"))
                );
                //2.若pend-list为空，则结束循环
                if (mapRecordList == null || mapRecordList.isEmpty()){
                    break;
                }
                //3.转换订单信息
                MapRecord<String, Object, Object> record = mapRecordList.get(0);
                Map<Object, Object> value = record.getValue();
                VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);

                // 4.创建订单
                handleVoucherOrder(voucherOrder);

                //5.确认消息
                stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());
            } catch (Exception e) {
                log.error("处理订单异常", e);
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
    }


    /*private class VoucherOrderHandler implements Runnable {
        @Override
        public void run() {
            while (true){
                try {
                    log.error("==================输出测试====================");
                    // 1.获取队列中的订单信息
                    VoucherOrder voucherOrder = orderTasks.take();
                    // 2.创建订单
                    handleVoucherOrder(voucherOrder);
                } catch (Exception e) {
                    log.error("处理订单异常", e);
                }
            }
        }
    }*/


    @Override
    public Result seckillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();//用户Id
        Long orderId = redisIdWorker.nextId("order");//订单Id

        //执行Lua脚本 判断是否有条件下单

        Long res = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(), orderId.toString()
        );

        //根据Lua脚本执行结果 判断是否有资格下单
        if (res != 0){
            String desc = res == 1 ? "库存不足" : "当前用户已下过单";
            return Result.fail(desc);
        }

        //保存优惠券信息到阻塞队列
        /*VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(UserHolder.getUser().getId());
        voucherOrder.setVoucherId(voucherId);*/
        //获取事务代理对象
        proxy = (IVoucherOrderService) AopContext.currentProxy();
//        orderTasks.add(voucherOrder);

        //返回订单Id
        return Result.ok(orderId);
    }

    /**
     * 优惠券下单
     * @param voucherOrder 优惠券信息
     */
    public void handleVoucherOrder(VoucherOrder voucherOrder){
        Long userId = voucherOrder.getUserId();
        //获取锁工具类
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        //获取锁
        boolean isLock = lock.tryLock();
        if (!isLock){
            //获取锁失败，这里是抢单业务，直接响应失败即可，无需重试
           log.error("不允许重复抢单！");
        }

        try {
            //获取代理对象，通过代理对象来调用方法 防止事务失效
            proxy.createVoucherOrder(voucherOrder);
        } finally {
            lock.unlock();
        }
    }

    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        Long voucherId = voucherOrder.getVoucherId();
        //4.根据用户Id和优惠券Id查询当前用户是否已下单
        Long userId = voucherOrder.getUserId();
        Integer count = this.query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        if (count > 0){
            log.error("当前用户已下单，无法重复下单!");
        }

        //5.扣减库存
        boolean success = seckillVoucherService.update()
                .setSql("stock= stock -1")
                .eq("voucher_id", voucherId).gt("stock",0).update();
        if (!success){
            log.error("库存不足!");
        }

        //5.创建订单
        this.saveOrUpdate(voucherOrder);
    }
}
